<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="课程ID" prop="courseId">
        <el-input
          v-model="queryParams.courseId"
          placeholder="请输入课程ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程名称" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属专业ID" prop="deptId">
        <el-input
          v-model="queryParams.deptId"
          placeholder="请输入所属专业ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="主讲教师ID" prop="teacherId">
        <el-input
          v-model="queryParams.teacherId"
          placeholder="请输入主讲教师ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="教师姓名" prop="teacherName">
        <el-input
          v-model="queryParams.teacherName"
          placeholder="请输入教师姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="教师所属院校" prop="teacherUniversity">
        <el-input
          v-model="queryParams.teacherUniversity"
          placeholder="请输入教师所属院校"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="选课容量" prop="capacity">
        <el-input
          v-model="queryParams.capacity"
          placeholder="请输入选课容量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="教师头像路径" prop="teacherAvatar">
        <el-input
          v-model="queryParams.teacherAvatar"
          placeholder="请输入教师头像路径"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程封面路径" prop="courseCover">
        <el-input
          v-model="queryParams.courseCover"
          placeholder="请输入课程封面路径"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开课学期" prop="semester">
        <el-input
          v-model="queryParams.semester"
          placeholder="请输入开课学期"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程代码" prop="courseCode">
        <el-input
          v-model="queryParams.courseCode"
          placeholder="请输入课程代码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['course:records:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['course:records:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['course:records:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['course:records:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="记录ID" align="center" prop="recordId" />
      <el-table-column label="课程ID" align="center" prop="courseId" />
      <el-table-column label="课程名称" align="center" prop="courseName" />
      <el-table-column label="所属专业ID" align="center" prop="deptId" />
      <el-table-column label="主讲教师ID" align="center" prop="teacherId" />
      <el-table-column label="教师姓名" align="center" prop="teacherName" />
      <el-table-column label="教师所属院校" align="center" prop="teacherUniversity" />
      <el-table-column label="学分" align="center" prop="credit" />
      <el-table-column label="选课容量" align="center" prop="capacity" />
      <el-table-column label="课程状态" align="center" prop="status" />
      <!-- <el-table-column label="教师头像路径" align="center" prop="teacherAvatar" />
      <el-table-column label="课程封面路径" align="center" prop="courseCover" /> -->
      <el-table-column label="开课学期" align="center" prop="semester" />
      <el-table-column label="课程代码" align="center" prop="courseCode" />
      <!-- <el-table-column label="课程简介" align="center" prop="courseBriefIntro" />
      <el-table-column label="课程介绍" align="center" prop="courseIntro" />
      <el-table-column label="教学目标" align="center" prop="courseGoals" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['course:records:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['course:records:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="课程ID" prop="courseId">
          <el-input v-model="form.courseId" placeholder="请输入课程ID" />
        </el-form-item>
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="form.courseName" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="所属专业ID" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入所属专业ID" />
        </el-form-item>
        <el-form-item label="主讲教师ID" prop="teacherId">
          <el-input v-model="form.teacherId" placeholder="请输入主讲教师ID" />
        </el-form-item>
        <el-form-item label="教师姓名" prop="teacherName">
          <el-input v-model="form.teacherName" placeholder="请输入教师姓名" />
        </el-form-item>
        <el-form-item label="教师所属院校" prop="teacherUniversity">
          <el-input v-model="form.teacherUniversity" placeholder="请输入教师所属院校" />
        </el-form-item>
        <el-form-item label="选课容量" prop="capacity">
          <el-input v-model="form.capacity" placeholder="请输入选课容量" />
        </el-form-item>
        <el-form-item label="教师头像路径" prop="teacherAvatar">
          <el-input v-model="form.teacherAvatar" placeholder="请输入教师头像路径" />
        </el-form-item>
        <el-form-item label="课程封面路径" prop="courseCover">
          <el-input v-model="form.courseCover" placeholder="请输入课程封面路径" />
        </el-form-item>
        <el-form-item label="开课学期" prop="semester">
          <el-input v-model="form.semester" placeholder="请输入开课学期" />
        </el-form-item>
        <el-form-item label="课程代码" prop="courseCode">
          <el-input v-model="form.courseCode" placeholder="请输入课程代码" />
        </el-form-item>
        <el-form-item label="课程简介" prop="courseBriefIntro">
          <el-input v-model="form.courseBriefIntro" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="课程介绍" prop="courseIntro">
          <el-input v-model="form.courseIntro" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="教学目标" prop="courseGoals">
          <el-input v-model="form.courseGoals" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRecords, getRecords, delRecords, addRecords, updateRecords, getRecordsByTeacherId } from "@/api/course/records"

export default {
  name: "Records",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程信息表格数据
      recordsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        courseId: null,
        courseName: null,
        deptId: null,
        teacherId: null,
        teacherName: null,
        teacherUniversity: null,
        credit: null,
        capacity: null,
        status: null,
        teacherAvatar: null,
        courseCover: null,
        semester: null,
        courseCode: null,
        courseBriefIntro: null,
        courseIntro: null,
        courseGoals: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        courseId: [
          { required: true, message: "课程ID不能为空", trigger: "blur" }
        ],
        courseName: [
          { required: true, message: "课程名称不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "所属专业ID不能为空", trigger: "blur" }
        ],
        teacherId: [
          { required: true, message: "主讲教师ID不能为空", trigger: "blur" }
        ],
        teacherName: [
          { required: true, message: "教师姓名不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    if (this.$store.state.user.roles.includes('teacher')) {
      this.queryParams.teacherId = this.$store.state.user.id
    } else {
      // 管理员保留原有查询参数
      delete this.queryParams.teacherId
    }
    this.getList()
  },
  methods: {
    /** 查询课程信息列表 */
    getList() {
      this.loading = true;
      console.log('当前查询参数:', JSON.stringify(this.queryParams));
      
      const apiCall = this.$store.state.user.roles.includes('admin') 
        ? listRecords(this.queryParams) 
        : getRecordsByTeacherId(this.queryParams.teacherId);

      apiCall
        .then(response => {
          console.log('完整API响应:', response);
          // 修改点：兼容直接返回rows和通过data.rows返回的两种格式
          const data = response.data || response;
          this.recordsList = data.rows || data || [];
          this.total = data.total || data.length || 0;
          
          console.log('处理后数据:', {
            recordsList: this.recordsList,
            total: this.total
          });
        })
        .catch(error => {
          console.error('请求失败详情:', error);
          this.$modal.msgError(`数据加载失败: ${error.message}`);
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        recordId: null,
        courseId: null,
        courseName: null,
        deptId: null,
        teacherId: null,
        teacherName: null,
        teacherUniversity: null,
        credit: null,
        capacity: null,
        status: null,
        teacherAvatar: null,
        courseCover: null,
        semester: null,
        courseCode: null,
        createTime: null,
        courseBriefIntro: null,
        courseIntro: null,
        courseGoals: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.recordId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加课程信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const recordId = row.recordId || this.ids
      getRecords(recordId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改课程信息"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.recordId != null) {
            updateRecords(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addRecords(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const recordIds = row.recordId || this.ids
      this.$modal.confirm('是否确认删除课程信息编号为"' + recordIds + '"的数据项？').then(function() {
        return delRecords(recordIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('course/records/export', {
        ...this.queryParams
      }, `records_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
